<template>
  <main class="home-page">
    <!-- 顶部：聊天输入区 -->
    <section class="hero">
      <div class="hero-content">
        <div class="title">
          <span class="brand">描述所想</span>
          <img src="../assets/logo.png" class="logo" alt="logo" />
          <span class="brand-accent">即刻生成</span>
        </div>
        <div class="subtitle">输入想法，输出网站 - 就这么简单</div>
        <!-- 用户Prompt输入框 -->
        <div class="chat-box">
          <a-textarea
            :bordered="false" 
            v-model:value="chatText"
            :rows="4"
            placeholder="使用 ZeroCodeGenerator 创建一个高效的小工具，帮我计算......"
            allow-clear
            :maxlength="1000"
          />
          <div class="char-counter">{{ (chatText || '').length }}/1000</div>
          <div class="chat-actions">
            <a-button type="primary" shape="circle" @click="onSend">
              <ArrowUpOutlined />
            </a-button>
          </div>
        </div>
        <!-- 快捷提示词按钮 -->
        <div class="quick-suggestions">
          <a-checkable-tag style="background: #fd7a68; border-style: dashed; color: white;" @click="minimalPersonalBlog">
            极简风个人博客
          </a-checkable-tag>
          <a-checkable-tag style="background: #34a269; border-style: dashed; color: white;" @click="writingCoursePlatform">
            写作课程平台
          </a-checkable-tag>
          <a-checkable-tag style="background: #55acee; border-style: dashed; color: white;" @click="imageCompressionTool">
            图片压缩工具
          </a-checkable-tag>
          <a-checkable-tag style="background: #cd201f; border-style: dashed; color: white;" @click="snakeGame">
            贪吃蛇小游戏
          </a-checkable-tag>
          <a-checkable-tag style="background: #3b5999; border-style: dashed; color: white;" @click="personalBlog">
            极客风个人博客
          </a-checkable-tag>

        </div>
      </div>
    </section>

    <!-- 底部：作品区 -->
    <section class="works">
      <div class="works-inner">
        <!-- 我的作品 -->
        <div class="section-header">
          <h3>我的作品</h3>
        </div>

        <div class="card-grid" v-if="hasMyApps">
          <div
            v-for="item in myPage.records"
            :key="item?.id"
            class="card-hover"
          >
<!--            <a-badge-ribbon-->
<!--              :text="getBadgeTextByType(<String>item?.codeGenType)"-->
<!--              size="small"-->
<!--              :color="getBadgeColorByType(<String>item?.codeGenType)"-->
<!--            >-->
              <a-card
                hoverable
                class="app-card"
              >
                <template #cover>
                  <img
                    :alt="item?.appName || 'cover'"
                    :src="item?.cover || defaultCover "
                  />
                </template>
                <a-card-meta
                  :title="item?.appName || '未命名应用'"
                  :description="`创建于：${formatDate(item?.createTime)}`"
                />
              </a-card>

<!--            </a-badge-ribbon>-->
            <!-- 查看对话、查看作品遮罩 -->
            <div
              v-if="item?.deployKey || item?.id"
              class="hover-actions"
            >
              <a-button
                v-if="item?.deployKey"
                class="btn btn-dark"
                size="large"
                @click.stop="viewWork(item)"
              >
                查看作品
              </a-button>
              <a-button
                v-if="item?.id"
                class="btn btn-light"
                size="large"
                @click.stop="viewChat(item?.id)"
              >
                查看对话
              </a-button>
            </div>
          </div>
        </div>
<!--        <div v-else class="empty-tip">
          暂无作品，试试在上方输入框描述你的想法开始创建吧～
        </div>-->

        <div class="pagination">
          <a-pagination
            :current="myQuery.pageNum || 1"
            :page-size="myQuery.pageSize || 8"
            :total="myPage.totalRow || 0"
            show-size-changer
            @change="onMyPageChange"
            @showSizeChange="onMyPageChange"
          />
        </div>

        <!-- 精选推荐 -->
        <div class="section-header mt-32">
          <h3>精选推荐</h3>
          <div class="toolbar">
            <a-select v-model:value="selectedSort" style="width: 120px" size="small">
              <a-select-option v-for="opt in sortOptions" :key="opt.value" :value="opt.value">
                {{ opt.label }}
              </a-select-option>
            </a-select>
          </div>
        </div>

        <div class="category-bar">
          <a-segmented v-model:value="activeCategory" :options="categories" size="small" />
        </div>

        <div class="card-row" v-if="hasGoodApps">
          <div
            v-for="item in goodPage.records"
            :key="item?.id"
            class="card-hover"
          >
<!--            <a-badge-ribbon-->
<!--              :text="getBadgeTextByType(<String>item?.codeGenType)"-->
<!--              size="small"-->
<!--              :color="getBadgeColorByType(<String>item?.codeGenType)">-->
              <a-card
                hoverable
                class="good-card"
              >
                <template #cover>
                  <img
                    :alt="item?.appName || 'cover'"
                    :src="item?.cover || defaultCover "
                  />
                </template>
                <a-card-meta
                  :title="item?.appName || '未命名应用'"
                  :description="formatDate(item?.createTime)"
                >
                  <template #avatar>
                    <a-avatar :src="item?.user?.userAvatar" />
                  </template>
                </a-card-meta>
              </a-card>
<!--            </a-badge-ribbon>-->
            <!-- 查看对话、查看作品遮罩 -->
            <div
              v-if="item?.deployKey || item?.id"
              class="hover-actions"
            >
              <a-button
                v-if="item?.deployKey"
                class="btn btn-dark"
                size="large"
                @click.stop="viewWork(item)"
              >
                查看作品
              </a-button>
              <a-button
                v-if="item?.id"
                class="btn btn-light"
                size="large"
                @click.stop="viewChat(item?.id)"
              >
                查看对话
              </a-button>
            </div>
          </div>
        </div>
        <div v-else class="empty-tip">
          暂无精选内容
        </div>

        <div class="pagination">
          <a-pagination
            :current="goodQuery.pageNum || 1"
            :page-size="goodQuery.pageSize || 8"
            :total="goodPage.totalRow || 0"
            show-size-changer
            @change="onGoodPageChange"
            @showSizeChange="onGoodPageChange"
          />
        </div>
      </div>
    </section>
  </main>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import { listMyAppVoByPage, listGoodAppVoByPage, chatToGenCode, addApp } from '@/api/appController.ts'
import {
  ArrowUpOutlined,
} from '@ant-design/icons-vue';
import { formatDate } from '@/utils/FormatDate';
import { useLoginUserStore } from '@/stores/LoginUserStore';
import { useRouter } from 'vue-router';
import { getDeployUrl } from '@/config/env.ts'
import {
  imageCompressionToolPrompt,
  minimalPersonalBlogPrompt,
  personalBlogPrompt,
  snakeGamePrompt, writingCoursePlatformPrompt
} from '@/prompt/RecommendedAppPrompt'
import { getBadgeColorByType } from '@/utils/CodeGenTypes.ts'
//默认封面图
const defaultCover = 'https://zero-code-generator-1332372410.cos.ap-guangzhou.myqcloud.com/empty-image/empty.png';
//路由
const router = useRouter();

// 用户Prompt输入框的输入内容
const chatText = ref('')

// 我的作品分页与数据
const myQuery = reactive<API.AppQueryRequest>({
  pageNum: 1,
  pageSize: 8,
  sortField: 'createTime',
  sortOrder: 'desc'
})

const myPage = reactive<API.PageAppVO>({
  records: [],
  pageNumber: 1,
  pageSize: 8,
  totalPage: 0,
  totalRow: 0
})
const myLoading = ref(false)

// 精选推荐分页与数据
const goodQuery = reactive<API.AppQueryRequest>({
  pageNum: 1,
  pageSize: 8,
  sortField: 'createTime',
  sortOrder: 'desc'
})
const goodPage = reactive<API.PageAppVO>({
  records: [],
  pageNumber: 1,
  pageSize: 8,
  totalPage: 0,
  totalRow: 0
})
const goodLoading = ref(false)

// 筛选占位（与示意图一致，可扩展为真实分类）
const categories = ['全部', '工具', '网站', '数据分析', '活动页面', '管理平台', '游戏']
const activeCategory = ref('全部')

// 排序占位
const sortOptions = [
  { label: '最新发布', value: 'latest' },
  { label: '热门作品', value: 'hot' }
]
const selectedSort = ref('latest')

/**
 * 监听排序 sortOptions 参数变化，重新查询数据
 */
watch(selectedSort, (newValue) => {
  if(newValue === 'latest'){
    goodQuery.sortField = 'createTime';
    goodQuery.sortOrder = 'desc';
    loadGoodApps();
  } else if(newValue === 'hot'){
    goodQuery.sortField = 'priority';
    goodQuery.sortOrder = 'desc';
    loadGoodApps();
  }
})

//==============================================示例Prompt===============================================

//点击添加图片压缩工具Prompt
const imageCompressionTool = () => {
  chatText.value = imageCompressionToolPrompt;
}
//点击添加贪吃蛇小游戏Prompt
const snakeGame = () => {
  chatText.value = snakeGamePrompt;
}
//点击添加极客风格个人博客Prompt
const personalBlog = () => {
  chatText.value = personalBlogPrompt;
}

//点击添加极简个人博客Prompt
const minimalPersonalBlog = () => {
  chatText.value = minimalPersonalBlogPrompt;
}

//点击添加写作课程平台Prompt
const writingCoursePlatform = () => {
  chatText.value = writingCoursePlatformPrompt;
}

//根据代码生成模式 CodeGenType 给徽标设置不同的文案
const getBadgeTextByType = (codeGenType:String) => {
  if(codeGenType === 'vue_project'){
    return 'VUE';
  }else if(codeGenType === 'html'){
    return 'HTML';
  } else if(codeGenType === 'multi_file'){
    return 'HTML多文件';
  }
}

// 加载“我的作品”
const loadMyApps = async () => {
  try {
    myLoading.value = true
    const res = await listMyAppVoByPage({ ...myQuery })
    if (res.data.code == 0 && res?.data.data) {
      myPage.records = res.data.data.records
      myPage.totalRow = res.data.data.totalRow
      myPage.totalPage = res.data.data.totalPage
    }
  } catch (e) {
    message.error('加载我的作品失败')
  } finally {
    myLoading.value = false
  }
}

// 加载“精选推荐”
const loadGoodApps = async () => {
  try {
    goodLoading.value = true
    const res = await listGoodAppVoByPage({
      ...goodQuery,
      // 可根据 activeCategory / selectedSort 调整查询参数
    })
    if (res.data.code == 0 && res?.data.data) {
      goodPage.records = res.data.data.records
      goodPage.totalRow = res.data.data.totalRow
      goodPage.totalPage = res.data.data.totalPage
    }
  } catch (e) {
    message.error('加载精选作品失败')
  } finally {
    goodLoading.value = false
  }
}

// 分页事件
const onMyPageChange = (page: number, size: number) => {
  myQuery.pageNum = page
  myQuery.pageSize = size
  loadMyApps()
}
const onGoodPageChange = (page: number, size: number) => {
  goodQuery.pageNum = page
  goodQuery.pageSize = size
  loadGoodApps()
}

/**
 * 发送用户输入Prompt，生成应用，生成成功后携带appId和用户Prompt跳转到代码生成页面
 */
const onSend = async () => {
  //用户输入的Prompt
  const userPrompt = chatText.value.trim()
  if (!userPrompt) {
    message.warning('请输入你的创意或需求')
    return
  }
  message.success('已收到你的创意，正在为你生成代码…')
  //1.创建应用（方法返回值为Long类型的AppID）
  const appRes = await addApp({
    initPrompt: userPrompt
  });
  if (appRes?.data.code == 0 && appRes?.data.data) {
      //应用ID
      const appId = String(appRes.data.data)
      //2.携带appId跳转到AI对话页面
      await router.push(`/app/chat/${appId}`)
    }else {
      message.error('应用生成失败，' + appRes?.data.message);
      return;
    }
}

// 查看对话
const viewChat = (appId: string | number | undefined) => {
  if (appId) {
    router.push(`/app/chat/${appId}?view=1`)
  }
}

// 查看作品（当应用已被成功部署后，即deployKey参数不为空）
const viewWork = (app: API.AppVO) => {
  if (app.deployKey) {
    const url = getDeployUrl(app.deployKey)
    window.open(url, '_blank')
  }
}

onMounted(() => {
  loadMyApps()
  loadGoodApps()
})

const hasMyApps = computed(() => (myPage.records?.length || 0) > 0)
const hasGoodApps = computed(() => (goodPage.records?.length || 0) > 0)
</script>

<style scoped>
/*主页中间logo图标样式*/
.logo {
  width: 32px;
  height: 32px;
  margin-left: 10px;
  margin-right: 10px;
  margin-bottom: 6.75px;
  border-radius: 20%;
  overflow: hidden; /* 确保图片内容不会超出圆形边界 */
  object-fit: cover; /* 如果.logo是img标签，这个属性可以让图片适应容器 */
}
/* 让布局的主内容背景透明，避免遮挡本页渐变背景 */
:deep(.main-content) {
  background: transparent !important;
}

/* 全屏渐变背景，铺满整个视口 */
.home-page {
  min-height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  /* 品牌蓝绿竖向渐变（上白下蓝），贴近示例图 */
  background: linear-gradient(
    180deg,
    #ffffff 0%,
    #f5f7f7 3%,
    #f9fcfc 5%,
    #f3f7f8 8%,
    #f0f8f9 15%,
    #e8fbff 26%,
    #b8f4f2 38%,
    #7fdde8 58%,
    #59bfe6 75%,
    #25baf5 86%,
    #3f8fe0 100%
  );
  background-attachment: fixed; /* 防止滚动出现断层 */
}

/* 顶部 Hero */
.hero {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 48px 20px 24px;
}
.hero-content {
  width: 45%;
  max-width: 980px;
  text-align: center;
}
.title {
  font-size: 32px;
  font-weight: 800;
  color: #0f172a;
  letter-spacing: 0.5px;
}
.brand { color: #0f172a; }
.brand-accent { color: #0ea5e9; }
.subtitle {
  margin-top: 8px;
  color: #475569;
}

.chat-box {
  position: relative;
  margin: 18px auto 8px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 8px 28px rgba(15, 23, 42, 0.06);
  padding: 12px;
}
/* 字数统计 */
.char-counter {
  position: absolute;
  left: 12px;
  bottom: 12px;
  font-size: 12px;
  color: #94a3b8; /* slate-400 */
  pointer-events: none;
}
.chat-box :deep(.ant-input) {
  font-size: 14px;
  min-height: 88px;
  border-radius: 8px;
}
.chat-actions {
  margin-top: 3px;
  display: flex;
  align-items: center;
  justify-content:end;
}

/* 主页AI对话框下面的快速建议tag布局 */
.quick-suggestions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
  justify-content: center;
}

/* 快速建议 tag 悬停反馈与点击指示 */
.quick-suggestions :deep(.ant-tag),
.quick-suggestions :deep(.ant-tag-checkable) {
  cursor: pointer;
  transition: transform .15s ease, box-shadow .15s ease, filter .15s ease;
}
.quick-suggestions :deep(.ant-tag:hover),
.quick-suggestions :deep(.ant-tag-checkable:hover) {
  transform: translateY(-1px) scale(1.03);
  box-shadow: 0 6px 16px rgba(15, 23, 42, 0.18);
  filter: brightness(1.06);
}

/* 作品区 */
.works {
  display: flex;
  justify-content: center;
  padding: 16px 20px 48px;
}
.works-inner {
  width: 100%;
  max-width: 1100px;
  background: #ffffff;
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 12px 32px rgba(15, 23, 42, 0.06);
}

/* 分区标题与工具条 */
.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.section-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 700;
  color: #0f172a;
}
.toolbar {
  display: flex;
  gap: 8px;
  align-items: center;
}

.category-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 14px 0 16px;
}

/* 我的作品卡片样式 */
.card-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 14px;
  margin-top: 15px;
}
.app-card {
  border-radius: 12px;
  overflow: hidden;
  padding: 0;
}

/* 精选作品卡片样式 */
.card-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 14px;
}
.good-card {
  border-radius: 12px;
  overflow: hidden;
  padding: 0;
}

/* 精选作品、我的作用卡片封面等比裁剪 */
.app-card :deep(.ant-card-cover), .good-card :deep(.ant-card-cover) {
  overflow: hidden;
  border-bottom: 1px solid #f1f5f9;
}
.app-card :deep(.ant-card-cover img), .good-card :deep(.ant-card-cover img) {
  width: 100%;
  height: 160px;
  object-fit: cover;
  display: block;
}

/* 分页器 */
.pagination {
  margin-top: 14px;
  display: flex;
  justify-content: center;
}

.mt-32 { margin-top: 32px; }

@media (max-width: 1024px) {
  .card-grid, .card-row {
    grid-template-columns: repeat(2, 1fr);
  }
}
@media (max-width: 640px) {
  .card-grid, .card-row {
    grid-template-columns: 1fr;
  }
}

/* 紧凑卡片样式：减少卡片内容区内边距与标题/描述间距 */
.app-card :deep(.ant-card-body),
.good-card :deep(.ant-card-body) {
  padding: 10px;
}

.app-card :deep(.ant-card-meta-title),
.good-card :deep(.ant-card-meta-title) {
  margin-bottom: 6px; /* 默认约为 16px，收紧 */
  font-size: 14px;
}

.app-card :deep(.ant-card-meta-description),
.good-card :deep(.ant-card-meta-description) {
  margin-top: 0;
  font-size: 12px;
  color: #64748b;
}
/* 悬浮操作层 */
.card-hover {
  position: relative;
}
.hover-actions {
  position: absolute;
  border-radius: 12px;
  inset: 0;
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: center;
  justify-content: center;
  background: rgba(15, 23, 42, 0.35); /* 半透明遮罩 */
  opacity: 0;
  visibility: hidden;
  transition: opacity .2s ease, visibility .2s ease;
  padding: 12px;
  z-index: 2;
}
.card-hover:hover .hover-actions {
  opacity: 1;
  visibility: visible;
}

/* 按钮风格（查看作品按钮黑，查看对话按钮白，圆角大胶囊） */
.hover-actions .btn {
  height: 44px;
  padding: 0 22px;
  border-radius: 999px;
  font-weight: 600;
  box-shadow: 0 8px 20px rgba(15,23,42,0.15);
  cursor: pointer;
  transition: transform .15s ease, box-shadow .15s ease, filter .15s ease;
}
.hover-actions .btn:hover {
  transform: translateY(-1px) scale(1.02);
  box-shadow: 0 10px 24px rgba(15,23,42,0.22);
}
.hover-actions .btn-dark {
  background: #0f172a;
  color: #fff;
  border: none;
}
.hover-actions .btn-dark:hover {
  background: #111827;
  color: #fff;
}
.hover-actions .btn-light {
  background: #fff;
  color: #0f172a;
  border: none;
}
.hover-actions .btn-light:hover {
  background: #f8fafc;
  color: #0f172a;
}
</style>